package me.jiatao.jetpack.room;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.os.Environment;

import java.io.File;

/**
 * Created by JiaTao on 2018/10/10.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
@Database(entities = {User.class, Book.class}, version = 1, exportSchema = false)
public abstract class UserDatabase extends RoomDatabase {
    private static final String DB_PATH = Environment.getExternalStorageDirectory() + "/room";
    private static final String DB_NAME = DB_PATH + "/UserDatabase.db";
    private static volatile UserDatabase instance;

    public static synchronized UserDatabase getInstance(Context context) {
        if (instance == null) {
            instance = create(context);
        }
        return instance;
    }

    private static UserDatabase create(final Context context) {
        File dbPathFile = new File(DB_PATH);
        if (!dbPathFile.exists()) {
            boolean mkdirsRes = dbPathFile.mkdirs();
            if (!mkdirsRes) {
                throw new RuntimeException("创建数据库文件夹失败");
            }
        }
        return Room.databaseBuilder(context, UserDatabase.class, DB_NAME)
                //允许主线程访问数据库
                .allowMainThreadQueries()
                .addMigrations()
                .build();
    }

    public abstract UserDao getUserDao();

    public abstract BookDao getBookDao();
}